package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {


    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        if(session.getAttribute(AuthServerConstant.LOGIN_USER)==null){
            return "login";
        }else{
            return "redirect:http://gulimall.com";
        }
    }

    @GetMapping("/reg.html")
    public String reg(){
        return "reg";
    }
    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){

        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);

        if(!StringUtils.isEmpty(s)){
            String[] split = s.split("_");
            if(System.currentTimeMillis() - Long.parseLong(split[1]) < 60000){
                return R.error(BizCodeEnume.SMS_EXCEPTION.getCode(),BizCodeEnume.SMS_EXCEPTION.getMsg());
            }
        }
        String codeRedis= (int) ((Math.random() * 9 + 1) * 100000) + "_" + System.currentTimeMillis();       //防止同一个手机在六十秒内再此发送
        String code = codeRedis.split("_")[0];
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,codeRedis,5, TimeUnit.MINUTES);
        R r = thirdPartyFeignService.sendCode(phone, code);
        return R.ok();
    }

    @Autowired
    MemberFeignService memberFeignService;

    @PostMapping("/regist")
    public String regist(@Validated UserRegistVo vo, BindingResult bindingResult,
                         RedirectAttributes redirectAttributes){
        //数据校验出错
        if(bindingResult.hasErrors()){
            //将错误的list收集成一个map
            Map<String, String> errors = bindingResult.getFieldErrors().stream()
                    .collect(Collectors.toMap(
                            FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            //request method "POST not support"
            //用户注册-》/regist[post]->转发/reg.html 路径映射默认都是get方式访问的

            //使用重定向解决了表单重复提交，提交一次数据就没了，利用session原理，将数据放在session中，
            // 只要跳到下一个叶面，数据就删掉 ， 会出现分布式session问题
            return  "redirect:http://auth.gulimall.com/reg.html";   //reg.html->reg是get,而提交的是Post,这里直接渲染reg,不再进行路径映射
        }

        //真正注册,调用远程服务器进行注册
        //校验验证码
        String code = vo.getCode();
        String val = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(val)){
            if(val.split("_")[0].equals(code)){
                //删除验证码,令牌机制
                //redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码通过，调用member服务，保存一个会员信息
                R r = memberFeignService.regist(vo);
                if(r.getCode()==0){
                 return "redirect:http://auth.gulimall.com/login.html";
                }else{
                    HashMap<String, String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                 return "redirect:http://auth.gulimall.com/reg.html";
                }

            }else{
                //验证码错误
                Map<String, String> errors = new HashMap<>();errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return  "redirect:http://auth.gulimall.com/reg.html";
            }
        //验证码已过期
        }else{
            Map<String, String> errors = new HashMap<>();errors.put("code","验证码已过期");
            redirectAttributes.addFlashAttribute("errors",errors);
            return  "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){

        R login = memberFeignService.login(vo);

        if(login.getCode()==0){
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirecct:http://gulimall.com";
        }else{
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg",login.getMsg());
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
